/**
 *说明：只显示单个元素
 * ("#d3").remove();
 * delete nodes['键名']，delete nodes[obj.target.name]
 * links=[]
 * graph(links)
 * */
// var links = [
//     { source: '氯达香豆素(药品)', target: '3', 'rela': '', type: 'resolved', groups: 3 },
//     { source: '氯达香豆素(药品)', target: '1', 'rela': '', type: 'resolved', groups: 1 },
//     { source: '氯达香豆素(药品)', target: '2', 'rela': '', type: 'resolved', groups: 2 },
//     { source: '氯达香豆素(药品)', target: '3', 'rela': '', type: 'resolved', groups: 3 },
//     { source: '氯达香豆素(药品)', target: '2', 'rela': '', type: 'resolved', groups: 2 },
//     { source: '氯达香豆素(药品)', target: '治疗心脏病用血管舒张药(药品)', entityId: '1567677479709304743', realName: '治疗心脏病用血管舒张药', semanticTag: '药品', 'rela': '是...的子类', type: 'resolved', groups: 0 },
//     { source: '氯达香豆素(药品)', target: '氯达香豆素(物质)', entityId: '1567677492336827877', realName: '氯达香豆素', semanticTag: '物质', 'rela': '有效成分', type: 'resolved', groups: 0 },
//     { source: '氯达香豆素(药品)', target: '氯达香豆素', 'rela': '名称', type: 'resolved', groups: 0 },
//     { source: '氯达香豆素(药品)', target: '11784193', 'rela': 'OMAHA概念ID', type: 'resolved', groups: 0 },
//     { source: '3', target: '老年人(人群)', entityId: '1567676794560080675', realName: '老年人', semanticTag: '人群', 'rela': '适用人群', type: 'resolved', groups: 3 },
//     { source: '1', target: '冠心病心绞痛(疾病)', entityId: '1567677480308565885', realName: '冠心病心绞痛', semanticTag: '疾病', 'rela': '适应证', type: 'resolved', groups: 1 },
//     { source: '2', target: '心力衰竭(疾病)', entityId: '1567677480303201803', realName: '心力衰竭', semanticTag: '疾病', 'rela': '适应证', type: 'resolved', groups: 2 },
//     { source: '3', target: '冠状动脉硬化(疾病)', entityId: '1567677479222158265', realName: '冠状动脉硬化', semanticTag: '疾病', 'rela': '适应证', type: 'resolved', groups: 3 },
//     { source: '2', target: '治疗用药(用药目的)2', entityId: '1567676794582572635', realName: '治疗用药', semanticTag: '用药目的', 'rela': '用药目的', type: 'resolved', groups: 2 },
//     { source: '3', target: '治疗用药(用药目的)3', entityId: '1567676794582572635', realName: '治疗用药', semanticTag: '用药目的', 'rela': '用药目的', type: 'resolved', groups: 3 },
//     { source: '1', target: '治疗用药(用药目的)1', entityId: '1567676794582572635', realName: '治疗用药', semanticTag: '用药目的', 'rela': '用药目的', type: 'resolved', groups: 1 }
// ];
var termLinks = [
  // { source: '氯达香豆素(药品)', target: '治疗心脏病用血管舒张药(药品)', entityId: '12350591', realName: '治疗心脏病用血管舒张药', semanticTag: '药品', 'rela': '子类', type: 'resolved', groups: 0 },
  // { source: '氯达香豆素(药品)', target: '氯达香豆素(物质)', entityId: '18537836', realName: '氯达香豆素', semanticTag: '物质', 'rela': '有效成分', type: 'resolved', groups: 0 },
  // { source: '氯达香豆素(药品)', target: '氯达香豆素', 'rela': '术语', type: 'resolved', groups: 0 },
  // { source: '氯达香豆素(药品)', target: '11784193', 'rela': 'OMAHA概念ID', type: 'resolved', groups: 0 },
  // 2
  // { source: '11q', target: 'b', 'rela': '3232', type: 'resolved', groups: 0 },
  // { source: '11q', target: 'c', 'rela': '32', type: 'resolved', groups: 1 },
  // { source: '11q', target: 'd', 'rela': '32', type: 'resolved', groups: 2 },
  // { source: '11q', target: 'dsfdsf', 'rela': '32', type: 'resolved', groups: 3 },
  // { source: '11q', target: 'e', 'rela': '32', type: 'resolved', groups: 6 },
  // { source: '11q', target: 'f', 'rela': '32', type: 'resolved', groups: 7 },
  // { source: 'dsfdsf', target: 'c', 'rela': '32', type: 'resolved', groups: 4 },
  // { source: 'dsfdsf', target: 'd', 'rela': '32', type: 'resolved', groups: 8 },
  // { source: 'dsfdsf', target: 'e', 'rela': '32', type: 'resolved', groups: 9 },
  // { source: 'dsfdsf', target: 'f', 'rela': '32', type: 'resolved', groups: 10 },
  // { source: 'dsfdsf', target: 'f', 'rela': '32', type: 'resolved', groups: 10 },
];
var nodes = {};
var data;
var searchType = "";
var $scaleExtent = [0.5, 1.5];//svg允许缩放最大最小值
var $imgPath = 'public/D3/img/';//图片相对位置
var extendNodeStopRefresh = false;//停止实时刷新【用于拓展节点时，拓展后继续实时刷新】,ture停止
var dataCirclePartition = {
  "children": [
    {
      // "name": "☿",
      "name": "unlockNowNode",
      "img": $imgPath + 'unlockNowNode.png'
    },
    {
      // "name": "✂",
      "name": "deleteNowNode",
      "img": $imgPath + 'deleteNowNode.png'
    },
    {
      // "name": "✠",
      "name": "extendNowNode",
      "img": $imgPath + 'extendNowNode.png'
    },
    {
      // "name": "오",
      "name": "lockAllNode",
      "img": $imgPath + 'lockAllNode.png'
    },
    {
      // "name": "◎",
      "name": "releaseAllNode",
      "img": $imgPath + 'releaseAllNode.png'
    },
    {
      // "name": "◎",
      "name": "docTargetNode",
      "img": $imgPath + 'docTargetNode.png'
    }
  ]
}
$(function () {
  (function () {
    $('#kg').css("font-weight", "bold");
    var num = getUrlParam("num");
    if (num == 501) {
      // searchType = "知识图谱";
      // getData(links);
      // graph(links);
    } else {
      // searchType = "术语";
      // getData(termLinks);
      // graph(termLinks);
      // getData(links);
      //             // graph(links);
    }
  })();
  $(document).keydown(function (event) {
    if (event.keyCode == 13) {
      var val = $("#search").val();
      if (val == '') {
        return;
      }
    }
  });
  // var flag = true;
  // $('#search').on('compositionstart',function(){
  //     flag = false;
  // });
  // $('#search').on('compositionend',function(){
  //     flag = true;
  // });
  //关键词索引
  // $("#kgKeyWord").on("change", function () {
  //     $("#choose").hide();
  //     $("#choose").html("");
  //     $("#choose").hide();
  //     var keyword = $("#search").val();
  //     if (keyword != ""){
  //         console.log(1234)
  //         getTerm(keyword);
  //     }
  // })
  //搜索框焦点改变事件
  $("#kgKeyWord").bind("input propotychange", function () {
    var keyWord = $(this).val();
    var type = $(this).attr("data-type");
    $(".kgSearchHint ul").html("");
    $(".kgSearchHint").hide();
    $(".kgResultHint").hide();
    if (keyWord != "") {
      // getTerm(keyWord,type);
    } else {
      $(".kgSearchHint").hide();
      $(".kgResultHint").hide();
      $(".kgSearchInput").css("border-top", "");
      $(".kgSearchInput").css("border-left", "");
    }
  });
});
// var timestampFlag = 0;
// function getTerm(keyword,type) {
//     var timestamp = (new Date()).valueOf();
//     var request = {text: keyword,type:type,timestamp:timestamp};
//     searchType = type;
//     $.ajax({
//         url: kgKeyWordUrl,
//         type: "POST",
//         // contentType: "application/json",
//         data: request,
//         success: function (data) {
//             if (data.ok) {
//                 if ($("#kgKeyWord").val() == ""){
//                     return;
//                 }
//                 var names = [];
//                 // var objs = eval('(' + data.result + ')');
//                 //
//                 var list = '';
//                 if(data.result){
//                     $.each(data.result, function (ids, obj,i) {
//                         var name = "'"+obj.name+"'";
//                         var semanticTag = "'"+obj.semanticTag+"'";
//                         var eid = "'"+obj.eid+"'";
//                         var num = ids+1;
//                         // list +='<li class="kgProposal searchTitleList" style="line-height:22px" data-num="'+num+'" onclick="getDetail(' + eid + ','+ name +','+ semanticTag +');">' + obj.name + '('+obj.semanticTag+')</li>';
//                         list +='<li class="kgProposal searchTitleList" style="line-height:22px" data-num="'+num+'" onclick="getDetail(' + eid + ','+ name +','+ semanticTag +','+ "'" + type + "'" +');"><span style="float:left">'+ obj.name +'</span><span style="float:right;margin-right:10px;">'+obj.semanticTag+'</span></li>';
//                     });
//                     if(data.timestamp>timestampFlag){
//                         if(data.result.length>0){
//                             $(".kgResultHint").show();
//                         }else{
//                             $(".kgResultHint").hide();
//                         }
//                         $(".kgSearchHint ul").html(list);
//                         $(".kgSearchHint").show();
//                         $(".kgSearchInput").css("border-top","1px solid #4A90E2");
//                         $(".kgSearchInput").css("border-left","1px solid #4A90E2");
//                          timestampFlag = data.timestamp;
//                     }
//                 }else{
//                     $(".kgSearchHint").hide();
//                     $(".kgResultHint").hide();
//                     $(".kgSearchInput").css("border-top","");
//                     $(".kgSearchInput").css("border-left","");
//                 }
//             }else {
//                 $(".hintBody span").html('目前仅对机构用户开放，详情请参阅<a href="https://www.omaha.org.cn/index.php?g=&m=article&a=index&id=22&cid=40" target="_black" style="color:#4A90E2">机构权益</a>。');
//                 $("#myAddTplHint").modal("show");
//                 // $(".kgSearchHint").html('<li class="kgProposal">' + data.message + '</li>');
//                 // $(".kgSearchHint").show();
//                 // $(".kgSearchInput").css("border-top","1px solid #4A90E2");
//                 // $(".kgSearchInput").css("border-left","1px solid #4A90E2");
//             }
//         }
//     });
// }
var force, nodes = [], edges = [], rawNodes, rawEdges; // 构建知识图谱需要操作的数据 (rawNodes, rawEdges将加载的原始构图数据缓存一份)
var svg;
var nodesDefArr = [];//最初查询结果
var colors = {};//颜色
var group = [];//颜色分组
function getData(links) {
  isClickContentText = true;
  $(".kgStickyNoteBtn").remove();
  nodes = {};
  $("#d3").remove();
  data = links;
  links.forEach(function (link) {
    link.source = nodes[link.sourceType + '@@' + link.sourceId] || (nodes[link.sourceType + '@@' + link.sourceId] = {
      id: link.sourceId,
      type: link.sourceType,
      name: link.source,
      content: link.sourceCont,
      groups: link.sourceGroups,
      targetTypParams: link.targetTypParams,
      nodeFloor: link.sourceNodeFloor,
    });
    link.target = nodes[link.targetType + '@@' + link.targetId] || (nodes[link.targetType + '@@' + link.targetId] = {
      id: link.targetId,
      type: link.targetType,
      extendType: link.targetExtendType,
      name: link.target,
      content: link.targetCont,
      groups: link.targetGroups,
      targetTypParams: link.targetTypParams,
      nodeFloor: link.targetNodeFloor
    });
    var $sourceGroups = link.sourceGroups;//关系的颜色
    var $targetGroups = link.targetGroups;//关系的颜色
    link.source.groups = $sourceGroups;
    link.target.groups = $targetGroups;
    nodesDefArr = nodes;
    // link.source = nodes[link.source] || (nodes[link.source] = {
    //   id: link.sourceId,
    //   name: link.source,
    //   content: link.sourceCont
    // });
    // link.target = nodes[link.target] || (nodes[link.target] = {
    //   id: link.targetId,
    //   name: link.target,
    //   content: link.targetCont
    // });
  });
  var attr = "";
  var attrs = [];
  var semanticTag = "";
  var semanticTags = [];
  var input1 = "";
  var input2 = "";
  var names = [];
  $.each(links, function (ids, obj) {
    // if (obj.rela != attr) {
    if (attrs.indexOf(obj.rela) == -1 && obj.rela != "" && obj.rela != "OMAHA概念ID") {
      input1 += '<button class="kgStickyNoteBtn kgAttr kgStickyNoteBtnSelect" data-num="1">' + obj.rela + '</button>';
      $("#kgWrap .kgStickyNoteBox").html(input1);
      // attr = obj.rela;
      attrs.push(obj.rela);
    }
    if (names.indexOf(obj.source.name) == -1) {
      names.push(obj.source.name)
    }
    // if (obj.semanticTag != semanticTags) {
    if (semanticTags.indexOf(obj.semanticTag) == -1) {
      if (obj.semanticTag != null && obj.semanticTag != "null") {
        input2 += '<button class="kgStickyNoteBtn kgSemanticTag kgStickyNoteBtnSelect" data-num="1">' + obj.semanticTag + '</button>';
        // console.log(input)
      }
      $("#kgWrap2 .kgStickyNoteBox").html(input2);
      // semanticTag = obj.semanticTag;
      semanticTags.push(obj.semanticTag);
    }
  });
  graph(links);//getdata()结束执行动画
  // 筛选属性关系
  $(".kgAttr").on("click", function () {
    $("#d3").remove();
    var dataNum = $(this).attr("data-num");
    var val = $(this).text();
    if (dataNum == 1) {
      var new_links = [];
      var new_links1 = [];
      var names2 = [];
      $.each(links, function (ids, obj) {
        if (val != obj.rela) {
          if (names2.indexOf(obj.source.name) == -1) {
            names2.push(obj.source.name)
          }
          new_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var del = [];
      $.each(names, function (ids, obi) {
        if (names2.indexOf(obi) == -1) {
          del.push(parseInt(obi))
        }
      });
      $.each(new_links, function (ids, obo) {
        if (del.indexOf(obo.groups) == -1) {
          new_links1.push(obo)
        }
      });
      links = new_links1;
    } else {
      var new_links = [];
      // console.log(links)
      var judge_links = data;
      var new1_links = [];
      var new2_links = [];
      $(this).parent().find("button[data-num=0]").each(function (i) {
        var vals = $(this).text();
        if (vals != val) {
          new1_links.push(vals)
        }
      });
      $.each(judge_links, function (ids, obj) {
        if (new1_links.indexOf(obj.rela) == -1) {
          new2_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var data2 = new2_links;
      nodes = {};
      $.each(new2_links, function (ids, obj) {
        nodes[obj.target.name] = obj.target;
        if (ids == 0) {
          nodes[obj.source.name] = obj.source;
        }
      });
      links = new2_links;
    }
    graph(links);
  });
  //筛选值的语义类型
  $(".kgSemanticTag").on("click", function () {
    $("#d3").remove();
    var val = $(this).text();
    var dataNum = $(this).attr("data-num");
    if (dataNum == 1) {
      var new_links = [];
      var new_links1 = [];
      var names2 = [];
      $.each(links, function (ids, obj) {
        if (val != obj.semanticTag) {
          if (names2.indexOf(obj.source.name) == -1) {
            names2.push(obj.source.name)
          }
          new_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var del = [];
      $.each(names, function (ids, obi) {
        if (names2.indexOf(obi) == -1) {
          del.push(parseInt(obi))
        }
      });
      $.each(new_links, function (ids, obo) {
        if (del.indexOf(obo.groups) == -1) {
          new_links1.push(obo)
        }
      });
      links = new_links1;
    } else {
      var new_links = [];
      var judge_links = data;
      var new1_links = [];
      var new2_links = [];
      $(this).parent().find("button[data-num=0]").each(function (i) {
        var vals = $(this).text();
        if (vals != val) {
          new1_links.push(vals)
        }
      });
      $.each(judge_links, function (ids, obj) {
        if (new1_links.indexOf(obj.semanticTag) == -1) {
          new2_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var data2 = new2_links;
      nodes = {};
      $.each(new2_links, function (ids, obj) {
        nodes[obj.target.name] = obj.target;
        if (ids == 0) {
          nodes[obj.source.name] = obj.source;
        }
      });
      links = new2_links;
    }
    graph(links);
  });
  //全选和取消全选
  $("#kgStickyNoteAll").click(function () {
    if ($(this).is(':checked')) {
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").attr("data-num", 1);
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").addClass("kgStickyNoteBtnSelect");
      $("#d3").remove();
      var new_links = [];
      // console.log(links)
      var judge_links = data;
      var new1_links = [];
      var new2_links = [];
      $(this).parent().parent().next("div").find("button[data-num=0]").each(function (i) {
        var vals = $(this).text();
        new1_links.push(vals)
      });
      $.each(judge_links, function (ids, obj) {
        if (new1_links.indexOf(obj.rela) == -1) {
          new2_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var data2 = new2_links;
      nodes = {};
      $.each(new2_links, function (ids, obj) {
        nodes[obj.target.name] = obj.target;
        if (ids == 0) {
          nodes[obj.source.name] = obj.source;
        }
      });
      links = new2_links;
      graph(links);
    } else {
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").attr("data-num", 0);
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").removeClass("kgStickyNoteBtnSelect");
      $("#d3").remove();
      var new_links = [];
      // console.log(links)
      var judge_links = data;
      var new1_links = [];
      var new2_links = [];
      var names2 = [];
      var new_links2 = [];
      $(this).parent().parent().next("div").find("button[data-num=0]").each(function (i) {
        var vals = $(this).text();
        new1_links.push(vals)
      });
      $.each(judge_links, function (ids, obj) {
        if (new1_links.indexOf(obj.rela) == -1) {
          if (names2.indexOf(obj.source.name) == -1) {
            names2.push(obj.source.name)
          }
          new2_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var data2 = new2_links;
      nodes = {};
      var del = [];
      $.each(names, function (ids, obi) {
        if (names2.indexOf(obi) == -1) {
          del.push(parseInt(obi))
        }
      });
      $.each(new2_links, function (ids, obj) {
        nodes[obj.target.name] = obj.target;
        if (ids == 0) {
          nodes[obj.source.name] = obj.source;
        }
        if (del.indexOf(obj.groups) == -1) {
          new_links2.push(obj)
        }
      });
      links = new_links2;
      graph(links);
    }
  });
  //全选和取消全选
  $("#kgStickyNoteAll2").click(function () {
    if ($(this).is(':checked')) {
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").attr("data-num", 1);
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").addClass("kgStickyNoteBtnSelect");
      $("#d3").remove();
      var new_links = [];
      var judge_links = data;
      var new1_links = [];
      var new2_links = [];
      $(this).parent().parent().next("div").find("button[data-num=0]").each(function (i) {
        var vals = $(this).text();
        new1_links.push(vals)
      })
      $.each(judge_links, function (ids, obj) {
        if (new1_links.indexOf(obj.semanticTag) == -1) {
          new2_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var data2 = new2_links;
      nodes = {};
      $.each(new2_links, function (ids, obj) {
        nodes[obj.target.name] = obj.target;
        if (ids == 0) {
          nodes[obj.source.name] = obj.source;
        }
      });
      links = new2_links;
      graph(links);
    } else {
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").attr("data-num", 0);
      $(this).parent().parent().next("div").find(".kgStickyNoteBtn").removeClass("kgStickyNoteBtnSelect");
      $("#d3").remove();
      var new_links = [];
      var judge_links = data;
      var new1_links = [];
      var new2_links = [];
      var names2 = [];
      var new_links2 = [];
      $(this).parent().parent().next("div").find("button[data-num=0]").each(function (i) {
        var vals = $(this).text();
        new1_links.push(vals)
      })
      $.each(judge_links, function (ids, obj) {
        if (new1_links.indexOf(obj.semanticTag) == -1) {
          if (names2.indexOf(obj.source.name) == -1) {
            names2.push(obj.source.name)
          }
          new2_links.push(obj);
        } else {
          delete nodes[obj.target.name];
        }
      });
      var data2 = new2_links;
      nodes = {};
      var del = [];
      $.each(names, function (ids, obi) {
        if (names2.indexOf(obi) == -1) {
          del.push(parseInt(obi))
        }
      });
      $.each(new2_links, function (ids, obj) {
        nodes[obj.target.name] = obj.target;
        if (ids == 0) {
          nodes[obj.source.name] = obj.source;
        }
        if (del.indexOf(obj.groups) == -1) {
          new_links2.push(obj)
        }
      });
      links = new_links2;
      graph(links);
    }
  })
}
function getDetail(eid, name, semanticTag, type) {
  $(".kgSearchHint").hide();
  $(".kgResultHint").hide();
  $(".kgSearchInput").css("border-top", "");
  $(".kgSearchInput").css("border-left", "");
  $("#kgKeyWord").val(name);
  // searchType = type;
  // var request = {eid: eid,name:semanticTag,type:type};
  // $.ajax({
  //     url: kgKeyWordDetail,
  //     type: "POST",
  //     // contentType: "application/json",
  //     data: request,
  //     success: function (data) {
  //         // console.log(data)
  //         if(data.ok){
  //             // var objs = eval('(' + data.result + ')');
  //             if (data.result) {
  //                 var datas = [];
  //                 $.each(data.result[0],function (ids,obj) {
  //                    var child = {};
  //                    if (obj.groups != 0){
  //                        child["source"] = obj.entityInfo[0]['name'];
  //                        child["target"] = (obj.groups).toString();
  //                        child["rela"] = '';
  //                        // child["target"] = "测试";
  //                        // child["rela"] = "cs";
  //                        child["type"] = "resolved";
  //                        child["groups"] = obj.groups;
  //                        child["realName"] = obj.val[0]['realName'];
  //                        if (obj.val[0].length > 1){
  //                            child['entityId']=obj.val[0]['valId'];
  //                            var index = obj.val[0]['name'].lastIndexOf("\(");
  //                            var tex  = d.name.substring(index+1,obj.val[0]['name'].length-1);
  //                            child['relation'] = tex;
  //                        }else {
  //                            child['entityId']='非实体';
  //                            child['relation'] = "";
  //                        }
  //                        datas.push(child);
  //                        // child["source"] = (obj.groups).toString();
  //                        // if(obj.val[0]['name']==undefined){
  //                        //     child["target"] = obj.val[0];
  //                        // }else{
  //                        //     child["target"] = obj.val[0]['name'];
  //                        // }
  //                        // child["rela"] = obj.relation[0]['name'];
  //                        // child["type"] = "resolved";
  //                        // child["groups"] = obj.groups;
  //                        // child["semanticTag"] = obj.semanticTag;
  //                        // datas.push(child)
  //                    }else {
  //                        child["source"] = obj.entityInfo[0]['name'];
  //                        if(obj.val[0]['name']==undefined){
  //                            child["target"] = obj.val[0];
  //                        }else{
  //                            child["target"] = obj.val[0]['name'];
  //                        }
  //                        child["rela"] = obj.relation[0]['name'];
  //                        // child["target"] = "测试";
  //                        // child["rela"] = "cs";
  //                        child["type"] = "resolved";
  //                        child["groups"] = obj.groups;
  //                        child["realName"] = obj.val[0]['realName'];
  //                        child["semanticTag"] = obj.semanticTag;
  //                        if (typeof(obj.val[0])!='string'){
  //                            child['entityId']=obj.val[0]['valId'];
  //                            index = obj.val[0]['name'].lastIndexOf("\(");
  //                            tex  =  obj.val[0]['name'].substring(index+1,obj.val[0]['name'].length-1);
  //                            child['relation'] = tex;
  //                        }else {
  //                            child['entityId']='非实体';
  //                            child['relation'] = "";
  //                        }
  //                        datas.push(child)
  //                    }
  //                 });
  //                 $.each(data.result[0],function (ids,obj) {
  //                     // console.log(obj.relation)
  //                     var child = {};
  //                     if (obj.groups != 0){
  //                         child["source"] = (obj.groups).toString();
  //                         if(obj.val[0]['name']==undefined){
  //                             child["target"] = obj.val[0]+(obj.groups).toString();
  //                         }else{
  //                             child["target"] = obj.val[0]['name']+(obj.groups).toString();
  //                         }
  //                         child["rela"] = obj.relation[0]['name'];
  //                         child["type"] = "resolved";
  //                         child["groups"] = obj.groups;
  //                         child["semanticTag"] = obj.semanticTag;
  //                         child["realName"] = obj.val[0]['realName'];
  //                         if (typeof(obj.val[0])!='string'){
  //                             child['entityId']=obj.val[0]['valId'];
  //                             var index = obj.val[0]['name'].lastIndexOf("\(");
  //                             var tex  = obj.val[0]['name'].substring(index+1,obj.val[0]['name'].length-1);
  //                             child['relation'] = tex;
  //                         }else {
  //                             child['entityId']='非实体';
  //                             child['relation'] = "";
  //                         }
  //                         datas.push(child)
  //                     }
  //                 });
  //                 // console.log(datas)
  //                 getData(datas);
  //                 graph(datas);
  //             }
  //         }else{
  //             if(data.code == 4051){
  //                 var message="操作过于频繁，请稍后再试。";
  //                 $("#publicHint5").modal("show");
  //                 $(".publicHint5Content span").text(message);
  //                 setTimeout(function(){
  //                     $("#publicHint5").modal("hide");
  //                 }, 1000);
  //             }
  //         }
  //     }
  // });
};
function graph(links) {
  colors = {
    // 0: '#D8E8F5', 1: '#CCCCFF', 2: '#F15E00', 3: '#30426A',
    0: '#5fb434', 1: '#57c7e3', 2: '#c990c0', 3: '#f79767',
    4: '#F3E2F0', 5: '#9142A1', 6: '#3EA27',
    7: '#F5A623', 8: '#91D5D0', 9: '#B391D5', 10: '#5BB2F0', 11: '#EF9898', 12: '#F2EC8A',
    13: '#B8E2A8', 14: '#E8C1E3', 15: '#91BEDF', 16: '#6A2D4C', 17: '#DAEFF4', 18: '#C52C31',
    19: '#AF7A50', 20: '#5EB97C', 21: '#80C2B4', 22: '#A7C4A5', 23: '#69916F', 24: '#A33035',
    25: '#774730', 26: '#A45A32', 27: '#B1D140', 28: '#853059', 29: '#EB5E57', 30: '#224747',
    31: '#B888BA', 32: '#C5B9C7', 33: '#F5A63C', 34: '#AB9E71', 35: '#929285', 36: '#20677D',
    37: '#ABBCBE', 38: '#6A2831', 39: '#407885', 40: '#207646', 41: '#F6D961', 42: '#E09C64',
    43: '#D18028', 44: '#2A406E', 45: '#B14D81', 46: '#39412C', 47: '#408B77', 48: '#707068',
    49: '#CEB5A1', 50: '#A76C66', 51: '#B4BAC8', 52: '#877195', 53: '#5FB6C7', 54: '#F7B96E',
    55: '#FBD3A0', 56: '#3B3C37', 57: '#95864A', 58: '#E1CADF', 59: '#E37F7B', 60: '#C4CC9D',
    61: '#F29689', 62: '#95B730', 63: '#218A71', 64: '#E0E9A7', 65: '#5B838D', 66: '#C8C8BD',
    67: '#49242C', 68: '#86A988', 69: '#AECA61', 70: '#706135', 71: '#42304A', 72: '#B69590',
    73: '#D594AA', 74: '#7F9C97', 75: '#8AADD7', 76: '#B03232', 77: '#2A3B81', 78: '#998CA0',
    79: '#CCBD9C', 80: '#F29A2B', 81: '#67BFA6', 82: '#98D4DF', 83: '#8598B8', 84: '#839144',
    85: '#87C793', 86: '#FFFFCC', 87: '#CCFFFF', 88: '#FFCCCC', 89: '#FFFF99', 90: '#FF9966',
    91: '#FFCC99', 92: '#CCFF99', 93: '#CCFFCC', 94: '#99CC99', 95: '#99CCCC', 96: '#FF6666',
    97: '#CCCCCC', 98: '#FF7CFD', 99: '#3CB3FF', 100: '#65FFBD'
  };
  group = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
    30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
    43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
    57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
    71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,
    86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
  ];
  var width = $(".kgView-box").width();
  var num = getUrlParam("num");
  var height = $(".kgView-box").height();
  // 定义力布局（数据转换）
  // nodes = nodes.concat(nodes); // 多数组连接
  // edges = edges.concat(links);
  // rawNodes = nodes;
  // rawEdges = edges;
  edges = links;
  // nodes = nodes;
  for (var i = 0; i < edges.length; i++) { // 关系数据添加INDEX值（为了方便对应图形元素）
    var obj = edges[i];
    obj.index = i;
  }
  // rawNodes = nodes;
  rawNodes = new Map();
  var nodes_i = 0;
  $.each(nodes, function (i, n) {
    rawNodes.put(nodes_i, n);
    nodes_i++;
    // addArrData(rawNodes, {n});
  });
  // edges = links;
  nodes = rawNodes.data;
  rawNodes = rawNodes.data;
  rawEdges = edges;
  force = d3.layout.force()
    .nodes(d3.values(nodes))
    .links(links)
    .size([width, height])// 指定范围
    .linkDistance(230)// 指定连线长度
    .charge(-1500)// 相互之间的作用力
    // .on("tick", tick)
    .start();
  svg = d3.select("#svg").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr('id', 'd3')
    .attr("z-index", 1)
    .append("g")
    .attr("id", "svgOne")
    .style('transform', 'translate(0, 0) scale(1)');
  // .call(d3.behavior.zoom() // 自动创建事件侦听器
  //   .scaleExtent($scaleExtent) // 缩放允许的级数
  //   .on("zoom", zoom)
  // )
  // .on("dblclick.zoom", null); // remove双击缩放;
  // 缩放函数
  dragSvg();//拖动
  function zoom() {
    // translate变换矢量（使用二元组标识）scale当前尺度的数字
    // svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); // 画布缩放与移动
    // $('#svgOne').css({"transform":"translate(" + d3.event.translate[0] + 'px,' + d3.event.translate[1] + "px)scale(" + d3.event.scale + ")"}); // 画布缩放与移动
    if ($('#svgOne').attr('data-input') == 'true') {
      d3.event.scale = Number($('#SvgRangeZoom').val()) / 100 + 0.5;
      $('#svgOne').attr('data-input', 'false');
    }
    $('#svgOne').attr('style', "transform:translate(" + d3.event.translate[0] + 'px,' + d3.event.translate[1] + "px)scale(" + d3.event.scale + ")");// 画布缩放与移动
// svg.attr("transform", "scale(" + d3.event.scale + ")"); // 画布缩放
    $('#SvgRangeZoom').val((d3.event.scale - 0.5) * 100);
    // $('#svgOne').on('click', function (e) {
    //   console.log(e.pageX, e.pageY)
    // })
  };
  buildGraph();
};
//添加扩展数据
var nodesAddArr = [];//存储，扩展node数据
var addNodes;
function graphAdd(linksAddNew) {
  if (linksAddNew.length > 0) {
    nodesAddArr = {};
    var linksAddNew_index = false;//判断遍历是否结束，关系数据添加INDEX值
    var nodesAddArr_raw = false;//判断遍历存入rawNodes、addNodes是否结束
    linksAddNew.forEach(function (link) {
      // link.source = nodesAddArr[link.sourceType + '@@' + link.sourceId] || (nodesAddArr[link.sourceType + '@@' + link.sourceId] = {
      //   id: link.sourceId,
      //   type: link.sourceType,
      //   name: link.source,
      //   content: link.sourceCont,
      //   groups: link.sourceGroups,
      // });
      link.source = nodesAddArr[link.sourceType + '@@' + link.sourceId] || (nodesAddArr[link.sourceType + '@@' + link.sourceId] = link.source);
      link.target = nodesAddArr[link.targetType + '@@' + link.targetId] || (nodesAddArr[link.targetType + '@@' + link.targetId] = {
        id: link.targetId,
        type: link.targetType,
        extendType: link.targetExtendType,
        name: link.target,
        content: link.targetCont,
        groups: link.targetGroups
      });
      var $sourceGroups = link.sourceGroups;//关系的颜色
      var $targetGroups = link.targetGroups;//关系的颜色
      link.source.groups = $sourceGroups;
      link.target.groups = $targetGroups;
      // nodesDefArr=nodes;
    });
    // edges = links;
    // nodes = nodes;
    for (var i = 0; i < linksAddNew.length; i++) { // 关系数据添加INDEX值（为了方便对应图形元素）
      var obj = linksAddNew[i];
      // obj.index = i + edges.length;
      // obj.target.index = i + nodes.length;
      // edges.push(linksAddNew[i]);
      // rawEdges.push(linksAddNew[i]);
      obj.index = rawEdges.length;
      obj.target.index = i + rawNodes.length;
      addArrData(edges, linksAddNew[i]);
      addArrData(rawEdges, linksAddNew[i]);
      var nodeAddValue = linksAddNew[i].target.type + '@@' + linksAddNew[i].target.id;
      nodesDefArr[nodeAddValue] = linksAddNew[i].target;
      if (i >= linksAddNew.length - 1) {
        linksAddNew_index = true;
        console.log(i)
      }
    }
    // edges.push(linksAddNew);
    // rawNodes = nodes;
    addNodes = new Map();
    var nodes_i = 0;
    $.each(nodesAddArr, function (i, n) {
      if (nodes_i == 0) {
        addNodes.put(nodes_i, n);
      } else {
        nodes.push(n);
        nodes = deteleObject(nodes);//数组对象去重，nodes/rawNodes单独添加数组会重逢，未找到原因
        rawNodes.push(n);
        rawNodes = deteleObject(rawNodes);//数组对象去重，nodes/rawNodes单独添加数组会重逢，未找到原因
        addNodes.put(nodes_i, n);
      }
      nodes_i++;
      if (nodes_i >= nodesAddArr.length) {
        nodesAddArr_raw = true;
        console.log('nodes_i', nodes_i)
      }
      // addArrData(rawNodes, {n});
    });
    extendNodePosition(linksAddNew);
  } else {
    // extendNodePosition();
    extendNodeBuildGraph();
  }
};
//遍历结束，添加节点位置
function extendNodePosition($links) {
  // rawEdges = edges;
  // setTimeout(function () {
  var width = $('#d3').width();
  var height = $('#d3').height();
  var $timeNum = nodes.length / 50;
  // setTimeout(function () {
  force = d3.layout.force()
  // force
  // .nodes(d3.values(nodesAddArr))
  // .links(linksAddNew)
    .nodes(d3.values(rawNodes))//之前用的nodes参数，解决剪切后扩展先关节点index变化bug
    // .nodes(d3.values(nodes))
    .links($links)
    .size([width, height])// 指定范围
    .linkDistance(230)// 指定连线长度
    .charge(-1500)// 相互之间的作用力
    // .on("tick", tick)
    .start();
  extendNodeBuildGraph();//拓展节点后-执行构建动画
  // },1000*$timeNum);
};
//拓展节点后-执行构建动画
function extendNodeBuildGraph() {
  d3.select("#svg").select("#svgOne").selectAll("*").remove(); // 清空SVG中的内容
  buildGraph();
  if ($('.kgViewImgBox>.loading-box').length > 0) {
    $('.kgViewImgBox>.loading-box').remove();
  }
};
//实时刷新关闭时，动画稳定后打开
function startRefreshTime() {
  var stopRefreshTime = setInterval(function () {
    clearInterval(stopRefreshTime);
    // force.stop(); // 渲染完成后立即停止刷新
    console.log('1', force.alpha());
    extendNodeStopRefresh = false;//停止实时刷新【用于拓展节点时，拓展后继续实时刷新】,ture停止
  }, 1000);
}
/************************start-graph*******************************/
var svg_edges, svg_nodes, svg_text, svg_text_edges; // 需要动态更新的函数(dynamic update function)
var circle, text, edges_line, edges_text;//各个节点定义
// Strat build Knowledge Graph/Vault
function buildGraph() {
  if (onlyOneNodeCircle) {
    //显示单个圆
    nodes = rawNodes = nodes.slice(0, 1, 1);
  }
  console.log("开始构建可视化知识图谱：");
  console.log(nodes);
  console.log(edges);
  //滑块input=range
  // $('#SvgRangeZoom').val(40);
  $('#SvgRangeZoom').attr('value', $('#SvgRangeZoom').val());
  $('#SvgRangeZoom').css('background', 'linear-gradient(to right, #059CFA, white ' + $('#SvgRangeZoom').val() + '%, white)');
  svg_edges = add_edges(); // 添加连线与箭头
  svg_nodes = add_nodes(); // 添加节点与文字
  svg_text_edges = add_text_edges(); // 添加描述关系的文字
  refresh();  // 对于每一个时间间隔进行更新
  force.resume(); // 必须添加否则图形元素更新不及时
  startRefreshTime();//实时刷新关闭时，动画稳定后打开
  if ($('.kgViewImgBox>.loading-box').length > 0) {
    $('.kgViewImgBox>.loading-box').remove();
  }
};
// 设置连线箭头属性
function setMarkers() {
  var marker =
    svg.append('g').attr('id', 'lineAndText')
    // .append("marker")
      .selectAll("marker")
      .data(edges)
      .enter()
      .append("marker")
      .attr("id", function (d) {
        return d.index;
      })
      // .attr("id", "resolved")
      .attr("markerUnits", "userSpaceOnUse")
      .attr("viewBox", "0 -5 10 10")
      .attr("refX", 32)
      .attr("refY", -1)
      .attr("markerWidth", 12)
      .attr("markerHeight", 12)
      .attr("orient", "auto")
      .attr("stroke-width", 2)
      .append("path")
      .attr("d", "M0,-5L10,0L0,5")
      .attr('fill', '#a5abb6');//箭头颜色
};
// 添加连线
function add_edges() {
  setMarkers(); // 设置连线箭头属性
  // edges_line = svg.append('g').attr('id', 'lineAndText').selectAll(".edgepath")
  edges_line = svg.select("#lineAndText")
    .attr('style', function () {
      if (onlyOneNodeCircle) {
        //显示单个圆
        return "display:none"
      }
    })
    .selectAll("line")
    .data(edges)
    .enter()
    .append("line")
    .attr({
      // 'd': function (d) {
      //   return 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y
      // },
      'class': 'edgepath',
      'id': function (d, i) {
        return d.index;
      }
    })
    .style("stroke", function (d) {
      var lineColor;
      lineColor = "#B43232";
      return lineColor;
    })
    .style("pointer-events", "none")
    .style("stroke-width", 0.5)
    .style("stroke-dasharray", function (d, i) {
      // console.log(d)
      if (d.annArg) {
        return '4'
      }
    })
    .attr("marker-end", function (d) {
      return "url(#" + d.index + ")";
    });
  // if (d.source.annArg || d.target.annArg) {
  //   edges_line.style("stroke-dasharray", 2.5)
  // }
};
// 添加描述关系文字
function add_text_edges() {
  edges_text = svg.select("#lineAndText")
    .selectAll("line.text")
    .data(edges)
    // .data(force.links())
    .enter()
    .append("text")
    .style("pointer-events", "none")
    // .attr("x", function (d) {
    //   return (d.source.x + d.target.x) / 2
    // })
    // .attr("y", function (d) {
    //   return (d.source.y + d.target.y) / 2
    // })
    .attr("x", function (d) {
      return (d.source.x + d.target.x) / 2
    })
    .attr("y", function (d) {
      return (d.source.y + d.target.y) / 2
    })
    .attr({
      'class': 'edgelabel',
      'id': function (d, i) {
        return d.index;
      },
      // 'x': 80,
      // 'y': 0
    });
  edges_text.text(function (d) {
    return d.rela;
  })
  // edges_text.append('textPath')
  //   .attr('xlink:href', function (d, i) {
  //     return '#edgepath' + i
  //   })
  //   .style("pointer-events", "none")
  //   .text(function (d) {
  //     return d.rela;
  //   });
};
// 添加节点
function add_nodes() {
  svg_nodes = svg.append("g")
    .attr('id', 'circleAndText')
    .selectAll("circle")
    // .data(force.nodes())
    .data(nodes)
    .enter()
    .append("g")
    .on("click", function (node) {
      edges_line.style("stroke-width", function (line) {
        if (line.source.name == node.name || line.target.name == node.name) {
          if (line.annArg) {
            return 2;//虚线加粗
          } else {
            return 4;
          }
          // return 4;
        } else {
          return 0.5;
        }
      });
      // 在当前节点处画三页扇形
      d3.select("#eee").remove();
      drawCirclePartition(node);
    })
    /*1.鼠标hover函数-start*/
    .call(force.drag().on("dragstart", function (d) {
        d3.select("#eee").remove(); // 删除节点扇形
        d3.select("#sel").remove(); // 删除节点选中
        d3.event.sourceEvent.stopPropagation(); // 画布拖动与节点拖动分离
        // d3.select(this).attr("r", 20 * 2);
      })
        .on("dragend", function (d) {
          d3.select("#eee").remove(); // 删除节点扇形
          d3.select("#sel").remove(); // 删除节点选中
          d.fixed = true; // 拖动结束后节点固定
          // d3.select(this).attr("r", 20);
        })
    )
    .on("mouseover", function (d) { // 鼠标选中时触发
      addToolTip(d); //添加提示框的div
    })
    .on("mouseout", function () {
      d3.select("#sel").remove(); // 删除节点选中
      d3.select("#tooltip").remove();
      d3.select("#tooltipCir").remove();
    });
  /*1.鼠标hover函数-end*/
  // .on("click", function (d) {
  //   // 在当前节点处画三页扇形
  //   d3.select("#eee").remove();
  //   drawCirclePartition(d);
  //   var tex = "";
  //   $.each(links, function (ids, obj) {
  //     if (obj.target.name == node.name) {
  //       if (typeof (obj.entityId) != 'undefined' && obj.entityId != "非实体") {
  //         tex = "getDetail('" + obj.entityId + "','" + obj.realName + "','" + obj.semanticTag + "','" + searchType + "')";
  //       } else {
  //         tex = "";
  //       }
  //     }
  //   });
  //   return tex;
  // });
  // .call(force.drag);
  svg_nodes.append("circle")
    .attr("id", function (d) {
      return d.index;
    })
    .style("fill", function (node) {
      // console.log(node)
      var color;
      // if (node.index == 1){
      //     node.index = 0
      // }else if (node.index == 0){
      //     node.index = 1
      // }
      if (node.index >= 0) {
        // console.log(node)
        /*var link = [];
        $.each(links, function (ids, obs) {
          // console.log(obs['source']['name']);
          if (node.name == obs['target']['name']) {
            // console.log(obs)
            link = obs
          }
        });
        // console.log(link.target)
        if (typeof (link) != "undefined") {
          if (group.indexOf(link.groups) != -1) {
            color = colors[link.groups];
            // color = "#f5e74c";
          } else {
            color = "#D8E8F5";
          }
        }*/
        color = colors[node.groups]
      } else {
        color = "#D8E8F5";
      }
      return color;
    })
    // .style('stroke', function (node) {
    //   var color;
    //   if (node.index != 0) {
    //     var link = links[node.index - 1];
    //     if (typeof (link) != "undefined") {
    //       if (link.rela == "代表作品") {
    //         color = "#49cbc8";
    //       } else {
    //         color = "#A254A2";
    //       }
    //     }
    //   } else {
    //     color = "#A254A2";
    //   }
    //   return color;
    // })
    .attr("r", function (node) {
      var r;
      //节点大小doc、typ
      if(nodeIdArr[node.type + '@@' + node.id]){
        var sizeNum = nodeIdArr[node.type + '@@' + node.id].sizeNum ? nodeIdArr[node.type + '@@' + node.id].sizeNum : '';
        r =  sizeNum;
        if(sizeNum === ''){
          r =  '28';
        }
      } else {
        r =  '28';
      }
      return r;
    });
  svg_nodes.append("svg:text")
  // .style("fill", "#ccc")
    .style('fill', function (node) {
      var color;
      var link = links[node.index];
      // color = "#A254A2";
      color = "#476da2";
      return color;
    })
    .attr("text-anchor", "middle")
    // .attr("dx", 20)
    // .attr("dy", 8)
    .text(function (d) {
      // return isEmpty(d.name)
      return enAndCnSubString(isEmpty(d.name), 8, false)
    });
  return svg_nodes;
};
// 对于每一个时间间隔进行更新
function refresh() {
  force.on("tick", function () { // 对于每一个时间间隔
    //图形趋于稳定0，初始1
    // if(force.alpha()<=0.05) {
    if (force.alpha() <= 0.05 || !extendNodeStopRefresh) {
      // function tick() {
      // svg_nodes.attr("transform", transform1);
      // 更新节点以及文字坐标
      svg_nodes.attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";
      });
      // svg_nodes.attr("transform", transform2);
      // edges_line.attr('d', function (d) {
      //   var path = 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y;
      //   return path;
      // });
      // 更新连线坐标·
      edges_line.attr("x1", function (d) {
        return d.source.x;
      })
        .attr("y1", function (d) {
          return d.source.y;
        })
        .attr("x2", function (d) {
          return d.target.x;
        })
        .attr("y2", function (d) {
          return d.target.y;
        });
      // edges_text.attr('transform', function (d, i) {
      //   if (d.target.x < d.source.x) {
      //     bbox = this.getBBox();
      //     rx = bbox.x + bbox.width / 2;
      //     ry = bbox.y + bbox.height / 2;
      //     return 'rotate(180 ' + rx + ' ' + ry + ')';
      //   } else {
      //     return 'rotate(0)';
      //   }
      // });
      // 更新关系文字坐标
      edges_text.attr("x", function (d) {
        return (d.source.x + d.target.x) / 2
      })
        .attr("y", function (d) {
          return (d.source.y + d.target.y) / 2
        });
      if (extendNodeStopRefresh) {
        force.stop(); // 渲染完成后立即停止刷新
      }
    }
  });
};
function linkArc(d) {
  return 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y
}
function transform1(d) {
  return "translate(" + d.x + "," + d.y + ")";
}
function transform2(d) {
  return "translate(" + (d.x) + "," + d.y + ")";
}
// 全局停止力作用之间的影响
function stopForce() {
  $.each(nodes, function (i, n) {
    var obj = n;
    obj.fixed = true;
  })
}
// 全局开始力作用之间的影响
function startForce() {
  $.each(nodes, function (i, n) {
    var obj = n;
    obj.fixed = false;
  })
  force.resume();
};
// 节点添加圆形分区（添加三页扇形）
function drawCirclePartition(d) {
  // 圆形分区布局（数据转换）
  var radius = 40;
  var partition = d3.layout.partition()
    .sort(null)
    .size([2 * Math.PI, radius * radius]) // 第一个值域时2 PI，第二个值时圆半径的平方
    .value(function (d) {
      return 1;
    });
  // 绘制圆形分区图
  // 如果以圆形的形式来转换数据那么d.x和d.y分别代表圆弧的绕圆心
  // 方向的起始位置和由圆心向外的起始位置d.dx和d.dy分别代表各自的宽度
  var arc = d3.svg.arc()
    .startAngle(function (d) {
      return d.x;
    })
    .endAngle(function (d) {
      return d.x + d.dx;
    })
    .innerRadius(function (d) {
      return 28;
    })
    .outerRadius(function (d) {
      return 80;
    });
  // var circlePart = partition.nodes(jsonDeepClone(dataCirclePartition));
  // docTargetNode
  // var $Circhildren ={
  //   'children':jsonDeepClone(dataCirclePartition.children.slice(0, 4))
  // }
  var circlePart;
  if (d.type == 'document') {
    circlePart = partition.nodes(jsonDeepClone(dataCirclePartition));
  } else {
    //节点不是doc，没有跳转按钮
    var $Circhildren = {'children': []};
    // $Circhildren.children = jsonDeepClone(dataCirclePartition.children.slice(0, 5));
    $Circhildren.children = jsonDeepClone(dataCirclePartition.children).filter(function (item){return  item.name !== 'docTargetNode'});
    circlePart = partition.nodes($Circhildren);
  }
  // "☿" 释放固定的节点
  function releaseNode() {
    d.fixed = false;
    // force.start(); // 开启或恢复结点间的位置影响
    force.resume();
  }
  // "✂" 删除当前节点以及当前节点到其它节点之间的关系
  function removeNode() {
    var newNodes = [];
    $.each(nodes, function (i, n) {
      var obj = n;
      if (obj.index != d.index) {
        newNodes.push(obj);
      }
    });
    // var newNodes = new Map();
    // $.each(nodes, function (i, n) {
    //   var obj = n;
    //   if (obj.index != d.index) {
    //     // newNodes.push(obj);
    //     newNodes.put(n.index,n);
    //   }
    // });
    // newNodes=newNodes.data
    var newedges = [];
    for (var i = 0; i < edges.length; i++) {
      var obj = edges[i];
      if ((d.index != obj.source.index) && (d.index != obj.target.index)) {
        newedges.push(obj);
      }
    }
    nodes = newNodes;
    edges = newedges;
    var nIndex = function (d) {
      return d.index;
    };
    var lIndex = function (d) {
      return d.index;
    };
    // 通过添加'g'元素分组删除
    svg.select("#circleAndText").selectAll("circle").data(nodes, nIndex)
      .exit()
      .remove();
    // svg.select("#circleAndText").selectAll("image")
    //   .data(nodes, nIndex)
    //   .exit()
    //   .remove();
    svg.select("#circleAndText").selectAll("text").data(nodes, nIndex)
      .exit()
      .remove();
    svg.select("#lineAndText").selectAll("line").data(edges, lIndex)
      .exit()
      .remove();
    svg.select("#lineAndText").selectAll("text").data(edges, lIndex)
      .exit()
      .remove();
  }
  // 判断元素是否在ARRAY中
  function isInArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (value === arr[i]) {
        return true;
      }
    }
    return false;
  }
  //  扩展当前节点，距离为1
  function extendNode() {
    /**arrEdges:存放于扩展节点相关节点的关系-edges
     * arrIndex：存放与扩展节点相关节点-index
     * arrNodes：存放于扩展节点相关节点-node
     */
    var index = d.index;
    var arrEdges = [], arrIndex = [], arrNodes = [];
    for (var i = 0; i < rawEdges.length; i++) {
      if ((index == rawEdges[i].source.index) || (index == rawEdges[i].target.index)) {
        arrEdges.push(rawEdges[i]);
        if (index != rawEdges[i].source.index) {
          addArrData(arrIndex, rawEdges[i].source.index);
          // arrIndex.push(rawEdges[i].source.index);
        } else if (index != rawEdges[i].target.index) {
          addArrData(arrIndex, rawEdges[i].target.index);
          // arrIndex.push(rawEdges[i].target.index);
        }
      }
    }
    for (var i = 0; i < rawNodes.length; i++) {
      for (var j = 0; j < arrIndex.length; j++) {
        var obj = arrIndex[j];
        if (rawNodes[i].index == obj) {
          arrNodes.push(rawNodes[i]);
        }
      }
    }
    // nodes.push(arrNodes);
    // edges.push(arrEdges);
    var nodesRemoveIndex = [];//已经展示的节点，不需要展示
    for (var i = 0; i < arrNodes.length; i++) {
      var obj = arrNodes[i];
      for (var j = 0; j < nodes.length; j++) {
        var obj2 = nodes[j];
        if (obj.index == obj2.index) {
          nodesRemoveIndex.push(i);
        }
      }
    }
    var edgesRemoveIndex = [];//已经展示的节点关系，不需要展示
    for (var i = 0; i < arrEdges.length; i++) {
      var obj = arrEdges[i];
      for (var j = 0; j < edges.length; j++) {
        var obj2 = edges[j];
        if (obj.index == obj2.index) {
          edgesRemoveIndex.push(i);
        }
      }
    }
    var coverNodes = [];//nodes中扩展进来的节点
    for (var i = 0; i < arrNodes.length; i++) {
      var obj = arrNodes[i];
      if (!isInArray(nodesRemoveIndex, i)) {
        nodes.push(obj);
        coverNodes.push(obj);
      }
    }
    var coverEdges = [];//edgs中扩展进来的关系
    for (var i = 0; i < arrEdges.length; i++) {
      var obj = arrEdges[i];
      if (!isInArray(edgesRemoveIndex, i)) {
        edges.push(obj);
        coverEdges.push(obj);
      }
    }
    // console.log("找出需要扩展的数据");
    // console.log(arrEdges);
    // console.log(arrNodes);
    // console.log("添加到原始数据集");
    // console.log(nodes);
    // console.log(edges);
    // d3.select("#svgGraph").remove(); // 删除整个SVG
    extendNodeOthers(d);
    // extendNodeBuildGraph();
    // d3.select("#svg").select("#svgOne").selectAll("*").remove(); // 清空SVG中的内容
    // buildGraph();
  };
  // 文档跳转到标注页面
  function docTargetNode() {
    var documentId = d.id;
    var projectId = getUrlParam('projectId');
    var projectTitle = getUrlParam('projectTitle');
    window.open(PUBLIC_PM.prefixUrl + "/projectManagement/taskBrat.html?type=manage&projectId=" + projectId + "&projectTitle=" + projectTitle + "&documentId=" + documentId);
  };
  var arcs = svg.append("g")
    .attr("id", "eee")
    .attr("transform", "translate(" + d.x + "," + d.y + ")")
    .selectAll("g")
    .data(circlePart)
    .enter()
    .append("g")
    .on("click", function (d) { // 圆形分区绑定Click事件
      if (d.name == "unlockNowNode") {
        releaseNode();
      }
      if (d.name == "deleteNowNode") {
        removeNode();
      }
      if (d.name == "extendNowNode") {
        extendNode();
      }
      if (d.name == "releaseAllNode") {
        startForce();
      }
      if (d.name == "lockAllNode") {
        stopForce();
      }
      if (d.name == "docTargetNode") {
        docTargetNode();//文档跳转到标注页面
      }
      d3.select("#eee").remove();
      d3.select("#tooltipCir").remove();
    });
  arcs.append("path")
    .attr("display", function (d) {
      return d.depth ? null : "none"; // hide inner ring
    })
    .attr("d", arc)
    .style("stroke", "#fff")
    // .style("fill", "#A9A9A9")
    .style("fill", "#A1DAFD")
    .on("mouseover", function (d) {
      // d3.select(this).style("fill", "#747680");
      d3.select(this).style("fill", "#0999F1");
      addToolTipCir(d); //添加提示框的div
    })
    .on("mouseout", function () {
      d3.select("#tooltipCir").remove();
      d3.select(this).transition()
        .duration(200)
        // .style("fill", "#ccc")
        .style("fill", "#A1DAFD")
      var array = printPosition();
      var distance = Math.sqrt(Math.pow((d.x - array[0]), 2) + Math.pow((d.y - array[1]), 2));
      if (distance > 80) {
        d3.select("#eee").remove(); // 删除节点扇形
      }
    });
  arcs.append("image")
    .attr('class', 'svgHoverImageIcon')
    .attr("transform", function (d, i) {
      // 平移和旋转
      // var r = 0;
      // if ((d.x + d.dx / 2) / Math.PI * 180 < 180) // 0-180度以内的
      //   r = 180 * ((d.x + d.dx / 2 - Math.PI / 2) / Math.PI);
      // else // 180-360度
      //   r = 180 * ((d.x + d.dx / 2 + Math.PI / 2) / Math.PI);
      // return "translate(" + arc.centroid(d) + ")" + "rotate(" + r + ")";
      var $translate = [];
      $translate[0] = Math.floor(arc.centroid(d)[0] * 100) / 100 - 5;
      $translate[1] = Math.floor(arc.centroid(d)[1] * 100) / 100 - 5;
      return "translate(" + $translate + ")" + "rotate(" + 0 + ")";
    })
    .attr('href', function (d) {
      return d.img
    })
  // arcs.append("text")
  //   .style("font-size", "16px")
  //   .style("font-family", "simsun")
  //   .style("fill", "white")
  //   .attr("text-anchor", "middle")
  //   .attr("transform", function (d, i) {
  //     // 平移和旋转
  //     var r = 0;
  //     if ((d.x + d.dx / 2) / Math.PI * 180 < 180) // 0-180度以内的
  //       r = 180 * ((d.x + d.dx / 2 - Math.PI / 2) / Math.PI);
  //     else // 180-360度
  //       r = 180 * ((d.x + d.dx / 2 + Math.PI / 2) / Math.PI);
  //     return "translate(" + arc.centroid(d) + ")" + "rotate(" + r + ")";
  //   })
  //   .text(function (d) {
  //     return d.name;
  //   });
  return arcs;
};
/************************end-graph*******************************/
//数组对象去重
function deteleObject(obj) {
  var uniques = [];
  var stringify = {};
  for (var i = 0; i < obj.length; i++) {
    var keys = Object.keys(obj[i]);
    keys.sort(function (a, b) {
      return (Number(a) - Number(b));
    });
    var str = '';
    for (var j = 0; j < keys.length; j++) {
      str += JSON.stringify(keys[j]);
      str += JSON.stringify(obj[i][keys[j]]);
    }
    if (!stringify.hasOwnProperty(str)) {
      uniques.push(obj[i]);
      stringify[str] = true;
    }
  }
  uniques = uniques;
  return uniques;
};
function clickEntity(eid) {
  alert(eid)
}
function unique1(arr) {
  var hash = [];
  for (var i = 0; i < arr.length; i++) {
    if (hash.indexOf(arr[i]) == -1) {
      hash.push(arr[i]);
    }
  }
  return hash;
}
/*hover函数添加start*/
//添加提示框的div
function addToolTip(d) {
  var htmlStr;
  // if (d.source && d.target && d.type) {
  //     htmlStr = "name:" + d.type + "<br/>";
  // } else {
  //     htmlStr = "id:" + d.id + "<br/>" + "name:" + d.name + "<br/>";
  // }
  htmlStr = "id:" + d.id + "<br/>" +
    // "name:" + d.name + "<br/>" +
    "content:" + d.content + "<br/>";
  var position = printPosition(d);
  var tooltip = d3.select("body").append("div")
    .attr("class", "tooltip") //用于css设置类样式
    .attr("opacity", 0.0)
    .attr("id", "tooltip");
  // htmlStr = htmlStr + "locx:" + position[0] + "<br/>" + "locy:" + position[1] + "<br/>";
  // if (d.image != undefined) {
  //   htmlStr = htmlStr + "<img src=\"" + $path_url + "/images/" + d.image + "\" height=\"100\" width=\"100\" />";
  // }
  tooltip.html(htmlStr)
    .style("left", (d3.event.pageX) + "px")
    .style("top", (d3.event.pageY + 20) + "px")
  // .style("opacity", 0.75);
};
// 实时获取SVG画布坐标
function printPosition() {
  // var position = d3.select("#svg").node().getBoundingClientRect();
  var position = d3.mouse(svg.node());
  return position;
};
function addToolTipCir(d) {
  var htmlStr;
  if (d.name == "unlockNowNode") {
    htmlStr = "notes:解锁当前节点<br/>";
  }
  if (d.name == "deleteNowNode") {
    htmlStr = "notes:裁剪当前节点与关系<br/>";
  }
  if (d.name == "extendNowNode") {
    htmlStr = "notes:拓展当前节点与关系<br/>";
  }
  if (d.name == "releaseAllNode") {
    htmlStr = "notes:释放所有锁定的节点<br/>";
  }
  if (d.name == "lockAllNode") {
    htmlStr = "notes:锁定所有节点<br/>";
  }
  if (d.name == "docTargetNode") {
    htmlStr = "notes:文档跳转到标注页面<br/>";
  }
  var tooltip = d3.select("body").append("div")
    .attr("class", "tooltip") //用于css设置类样式
    .attr("opacity", 0.0)
    .attr("id", "tooltipCir");
  tooltip.html(htmlStr)
    .style("left", (d3.event.pageX) + "px")
    .style("top", (d3.event.pageY + 20) + "px")
    .style("opacity", 0.75);
}
// dragSvg();
/********************滑动缩放svg-start****************************/
//滑动缩放svg
$('#SvgRangeZoom').change(function () {
  // console.log($(this).val());
  var $thisSale = Number($(this).val());
  var $html = $('#svgOne');
  var $matrix = getTransform($html);//获取元素transform-css
  var $svgOneTransform = [];
  var $svgOneScale = [];
  var rangeMin = $('#SvgRangeZoom').attr('min');
  var rangeMan = $('#SvgRangeZoom').attr('max');
  var step = ($scaleExtent[1] - $scaleExtent[0]) / (Number(rangeMan) - Number(rangeMin));//(倍数/步数)
  $svgOneScale = $thisSale * (1 / 100) + 0.5;
  $svgOneTransform.push($matrix[4]);
  $svgOneTransform.push($matrix[5]);
  $('#svgOne').attr('data-input', 'ture');
  $('#svgOne').attr('style', 'transform:translate(' + Number($svgOneTransform[0]) + 'px,' + Number($svgOneTransform[1]) + 'px) scale(' + $svgOneScale + ');-webkit-transform-origin: 50% 50% 0;-moz-transform-origin:50% 50% 0;');
});
//倍数-减小
$('#svgReduceImg').on('click', function (e) {
  // e.stopPropagation();
  if (e.target == this) {
    SvgRangeZoomNarrow();//svg缩小
  }
});
//倍数-变大
$('#svgIncreseImg').on('click', function () {
  SvgRangeZoomEnlarge();//svg放大
});
//svg滚轮放大缩小
var myimage = document.getElementById("svg");
if (myimage.addEventListener) {
  // IE9, Chrome, Safari, Opera
  myimage.addEventListener("mousewheel", MouseWheelHandler, false);
  // Firefox
  myimage.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
function MouseWheelHandler(e) {
//滚轮
  var e = window.event || e;
  var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
  if (delta > 0) {
    //放大
    SvgRangeZoomEnlarge();
  } else if (delta < 0) {
    //缩小
    SvgRangeZoomNarrow();
  }
  return false;
};
//svg放大
function SvgRangeZoomEnlarge() {
  var $val = Number($('#SvgRangeZoom').val());
  if ($val < 100) {
    $val = $val + 5;
    $('#SvgRangeZoom').val($val);
    var $html = $('#svgOne');
    var $matrix = getTransform($html);//获取元素transform-css
    $('#SvgRangeZoom').attr('value', $val);
    $('#SvgRangeZoom').css('background', 'linear-gradient(to right, #059CFA, white ' + $val + '%, white)');
    $svgOneScale = Number($matrix[0]) + 5 / 100;
    $svgOneTransform[0] = Number($matrix[4]);
    $svgOneTransform[1] = Number($matrix[5]);
    $('#svgOne').attr('style', 'transform:translate(' + Number($svgOneTransform[0]) + 'px,' + Number($svgOneTransform[1]) + 'px) scale(' + $svgOneScale + ');-webkit-transform-origin: 50% 50% 0;-moz-transform-origin:50% 50% 0;');
  }
};
//svg缩小
function SvgRangeZoomNarrow() {
  var $val = Number($('#SvgRangeZoom').val());
  if ($val > 1) {
    $val = $val - 5;
    $('#SvgRangeZoom').val($val);
    var $html = $('#svgOne');
    var $matrix = getTransform($html);//获取元素transform-css
    $('#SvgRangeZoom').attr('value', $val);
    $('#SvgRangeZoom').css('background', 'linear-gradient(to right, #059CFA, white ' + $val + '%, white)');
    $svgOneScale = Number($matrix[0]) - 5 / 100;
    $svgOneTransform[0] = Number($matrix[4]);
    $svgOneTransform[1] = Number($matrix[5]);
    $('#svgOne').attr('style', 'transform:translate(' + Number($svgOneTransform[0]) + 'px,' + Number($svgOneTransform[1]) + 'px) scale(' + $svgOneScale + ');-webkit-transform-origin: 50% 50% 0;-moz-transform-origin:50% 50% 0;');
  }
};
/********************滑动缩放svg-end****************************/
//获取元素transform-css
function getTransform($html) {
  //获取 transform 值
  var reg = /matrix.(((-)?([0-9]+.)?\d+([, ]+)?){6})./g;
  var str = $html.css("transform");
  //str  =  matrix(1, 0, 0, 1, 0, 0)
  var arr = reg.exec(str);
  var newarr = arr[1].split(/[, ]+/g);
  //newarr = ["1", "0", "0", "1", "0", "0"]
  // console.log(newarr);
  return newarr;
};
var $svgOneTransform = [];//拖动，存放平移变量
var $svgOneScale = '';//拖动，存放放大倍数
var settime;//定时器，平移SVG
//left
$(document).on('mousedown', '#svgLeftImg', function () {
  $svgOneTransform = [];
  var $html = $('#svgOne');
  var $matrix = getTransform($html);//获取元素transform-css
  $svgOneScale = $matrix[0];
  $svgOneTransform[0] = Number($matrix[4]);
  $svgOneTransform[1] = Number($matrix[5]);
  settime = setInterval(function () {
    $svgOneTransform[0] = Number($svgOneTransform[0]) - 1;
    $svgOneTransform[1] = Number($svgOneTransform[1]);
    $('#svgOne').css("transform", 'translate(' + (Number($svgOneTransform[0])) + 'px,' + (Number($svgOneTransform[1])) + 'px) scale(' + $svgOneScale + ')');
  }, 10);
});
//right
$(document).on('mousedown', '#svgRightImg', function () {
  $svgOneTransform = [];
  var $html = $('#svgOne');
  var $matrix = getTransform($html);//获取元素transform-css
  $svgOneScale = $matrix[0];
  $svgOneTransform[0] = Number($matrix[4]);
  $svgOneTransform[1] = Number($matrix[5]);
  settime = setInterval(function () {
    $svgOneTransform[0] = Number($svgOneTransform[0]) + 1;
    $svgOneTransform[1] = Number($svgOneTransform[1]);
    $('#svgOne').css("transform", 'translate(' + (Number($svgOneTransform[0])) + 'px,' + (Number($svgOneTransform[1])) + 'px) scale(' + $svgOneScale + ')');
  }, 10);
});
//up
$(document).on('mousedown', '#svgUpImg', function () {
  $svgOneTransform = [];
  var $html = $('#svgOne');
  var $matrix = getTransform($html);//获取元素transform-css
  $svgOneScale = $matrix[0];
  $svgOneTransform[0] = Number($matrix[4]);
  $svgOneTransform[1] = Number($matrix[5]);
  settime = setInterval(function () {
    $svgOneTransform[0] = Number($svgOneTransform[0]);
    $svgOneTransform[1] = Number($svgOneTransform[1]) - 1;
    $('#svgOne').css("transform", 'translate(' + (Number($svgOneTransform[0])) + 'px,' + (Number($svgOneTransform[1])) + 'px) scale(' + $svgOneScale + ')');
  }, 10);
});
//down
$(document).on('mousedown', '#svgDownImg', function () {
  $svgOneTransform = [];
  var $html = $('#svgOne');
  var $matrix = getTransform($html);//获取元素transform-css
  $svgOneScale = $matrix[0];
  $svgOneTransform[0] = Number($matrix[4]);
  $svgOneTransform[1] = Number($matrix[5]);
  settime = setInterval(function () {
    $svgOneTransform[0] = Number($svgOneTransform[0]);
    $svgOneTransform[1] = Number($svgOneTransform[1]) + 1;
    $('#svgOne').css("transform", 'translate(' + (Number($svgOneTransform[0])) + 'px,' + (Number($svgOneTransform[1])) + 'px) scale(' + $svgOneScale + ')');
  }, 10);
});
//清除循环移动
$(document).on('mouseup', '#svgLeftImg', function () {
  clearInterval(settime);
});
$(document).on('mouseup', '#svgRightImg', function () {
  clearInterval(settime);
});
$(document).on('mouseup', '#svgUpImg', function () {
  clearInterval(settime);
});
$(document).on('mouseup', '#svgDownImg', function () {
  clearInterval(settime);
});
$(document).on('mousemove', '#svgLeftImg,#svgRightImg,#svgUpImg,#svgDownImg', function () {
  clearInterval(settime);
});
//SVG拖动
function dragSvg() {
  var dragSvgarr1 = [];//拖动前位置
  var dragSvgarr2 = [];//拖动后位置
  var dragging = true;//拖动事件
  // $(document).bind('dragstart', '#svgOne', function (e) {
  $(document).bind('mousedown', '#svgOne', function (e) {
    //阻止冒泡，阻止子元素冒泡【阻止#eee鼠标点击拖动】
    if (e.target.tagName == 'svg') {
      dragging = true;
      // console.log(e.pageX,e.pageY);
      dragSvgarr1 = [];
      $svgOneTransform = [];
      dragSvgarr1.push(e.pageX);
      dragSvgarr1.push(e.pageY);
      var $html = $('#svgOne');
      var $matrix = getTransform($html);//获取元素transform-css
      $svgOneScale = $matrix[0];
      $svgOneTransform[0] = $matrix[4];
      $svgOneTransform[1] = $matrix[5];
      $(document).bind('mousemove', '#svgOne', function (e) {
        if (dragging) {
          // console.log(e.pageX,e.pageY);
          dragSvgarr2 = [];
          dragSvgarr2.push(e.pageX);
          dragSvgarr2.push(e.pageY);
          drag(dragSvgarr1, dragSvgarr2);
        }
      });
      $(document).bind('mouseup', '#svgOne', function (e) {
        dragging = false;
      });
      // $(document).bind('dragend', '#svgOne', function (e) {
      //   dragging = false;
      // });
    }
  });
  function drag(arr1, arr2) {
    if (arr1.length > 0 && arr2.length > 0) {
      var x = arr2[0] - arr1[0];
      var y = arr2[1] - arr1[1];
      // console.log(arr1, arr2, x, y);
      $('#svgOne').css("transform", 'translate(' + (Number($svgOneTransform[0]) + x) + 'px,' + (Number($svgOneTransform[1]) + y) + 'px) scale(' + $svgOneScale + ')');
    }
  };
};
/*hover函数添加end*/